'use strict';

const Controller = require('egg').Controller;
const jwt = require('jsonwebtoken');

class UserController extends Controller {
    //注册的函数
    async registry() {
        const { ctx,service } = this;
        //获取前端传递的参数
        let {username,phone,password} = ctx.request.body;

        //容错处理

        if(username && /\d{11}/.test(phone) && password){

            let target = await service.user.selectUser(username);
            console.log(target)
            if(target.length){
                //已经注册ok
                ctx.body = {
                    code:3,
                    msg:'此用户名已注册'
                }
            }else{
                //ctx.helper
                let hmcPwd = ctx.helper.hmc(password); //加密之后的密码

                try{
                   await service.user.registry(username,hmcPwd,phone);
                    ctx.body = {
                        code:1,
                        msg:'注册成功'
                    }
                }catch(e){
                    ctx.body = {
                        code:0,
                        msg:'注册失败'
                    }
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数有误'
            }
        }
    }

    //登录
    async login(){
        let {ctx,service} = this;
        //获取用户名和密码
        let {username,password} = ctx.request.body;
        //1.容错处理
        if(username && password){
             let hmcPwd = ctx.helper.hmc(password);
             let user = await service.user.login(username,hmcPwd);//[]
             if(user.length){
                 let token = jwt.sign({username},'1710A',{expiresIn:5*60*60});
                 ctx.body = {
                     code:1,
                     msg:'登录成功',
                     token
                 }
             }else{
                 ctx.body = {
                     code:0,
                     msg:'登录失败'
                 }
             }
        }else{
            ctx.body = {
                code:0,
                msg:'参数有误'
            }
        }
    }
}

module.exports = UserController;
